// import { login, getUserInfo, logout } from '@/api/user'
// import { getToken, setToken, setUser, getUser, removeToken } from '@/util/auth'
import { Login, GetUserInfo } from '@/api/user'
import { setToken, getToken, setUser, getUser, removeToken, setTokenExpiresTime, getTokenExpiresTime } from '@/util/auth'
const user = {
    state: {
        token: getToken(),
        user: getUser(),
        tokenExpiresTime: getTokenExpiresTime()
    },
    mutations: {
        SET_TOKEN(state, obj) {
            const { token, tokenExpiresTime } = obj;
            state.token = token;
            state.tokenExpiresTime = tokenExpiresTime;
            setToken(token);
            setTokenExpiresTime(tokenExpiresTime);
        },
        SET_USER(state, user) {
            state.user = user;
            setUser(user);
        }
    },
    actions: {
        // 登录
        async LoginFun({ commit }, data) {
            var res = await Login(data);
            if (res.isSuccess) {
                commit('SET_TOKEN', { token: 'Bearer ' + res.data.token, tokenExpiresTime: res.data.expiresTimeStr });
                var resUser = await GetUserInfo();
                commit('SET_USER', resUser.data)
            }
            // return resolve(res);
            return res;
        },
        async RefreshFun({ commit }, data) {
            const { token, tokenExpiresTime } = data;
            commit('SET_TOKEN', { token: 'Bearer ' + token, tokenExpiresTime: tokenExpiresTime });
            var resUser = await GetUserInfo();
            commit('SET_USER', resUser.data)
        },
        async GetUserInfoFun({ commit }) {
            var res = await GetUserInfo();
            commit('SET_USER', res.data)
        },

        // 退出登录
        LogoutFun({ commit }) {
            //todo 对接后端
            commit('SET_TOKEN', {})
            commit('SET_USER', {});
            removeToken();
        },

    },
    getters: {
        token: state => state.token,
        user: state => state.user,
    }
}
export default user
